package top.someapp.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import java.lang.reflect.Field;
import top.someapp.R;
import top.someapp.annotation.BindView;

/**
 * @author zwz
 * Created on 2021-07-22
 */
public abstract class BaseFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        int layoutId = getFragmentLayoutId();
        if (layoutId <= 0) {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
        return inflater.inflate(layoutId, container, false);
    }

    @Override public void onStart() {
        super.onStart();
        bindView();
        initView();
        addListeners();
        onReady();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    protected final void replaceSelfTo(@NonNull Fragment target) {
        FragmentActivity activity = getActivity();
        if (activity instanceof BaseFragmentActivity) {
            ((BaseFragmentActivity) activity).replaceFragment(target);
        }
    }

    protected @LayoutRes int getFragmentLayoutId() {
        return 0;
    }

    protected <T extends View> T findViewById(@IdRes int id) {
        return getActivity().findViewById(id);
    }

    protected void initView() {}

    private void bindView() {
        Field[] fields = getClass().getDeclaredFields();
        if (fields.length < 1) return;
        for (Field field : fields) {
            try {
                if (field.isAnnotationPresent(BindView.class)) {
                    BindView annotation = field.getAnnotation(BindView.class);
                    int id = annotation.value();
                    if (id > 0) {
                        field.set(this, findViewById(id));
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    protected void addListeners() {}

    protected void onReady() {}
}
